﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ComputerGraphics.Graphics;
using ComputerGraphics.Utils;

namespace ComputerGraphics.Geometry
{
    public class Polygon : Plane
    {
        protected List<Point3D> vertices;

        public Polygon(List<Point3D> vertices, Texture texture)
            : base(vertices[0], vertices[1] - vertices[0], vertices[vertices.Count - 1] - vertices[0], texture)
        {
            if (vertices != null)
                this.vertices = new List<Point3D>(vertices);
            else
                this.vertices = new List<Point3D>();
            this.vertices.Add(vertices[0]);
        }

        public override Intersection Intersect(Ray r)
        {
            Intersection ret = base.Intersect(r);
            
            if (ret != null)
            {
                int idx = 1;
                Point3D prev = (vertices[0] - ret.Position).Direction;
                double sum = 0;

                while (idx < vertices.Count)
                {
                    Point3D current = (vertices[idx] - ret.Position).Direction;
                    Point3D cr = prev ^ current;

                    double ns = cr.Norm * MathUtils.GetDoubleSign(cr * normal);
                    double nc = prev * current;

                    sum += Math.Atan2(ns, nc);

                    prev = current;
                    idx++;
                }

                if (MathUtils.GetZeroDouble(Math.Abs(sum) - 2 * Math.PI) != 0)
                    ret = null;
            }

            return ret;
        }

    }
}
